﻿/*
 * @author: wizardc
 */

using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using UnityEngine.UI;

namespace Dou.UI
{
    /// <summary>
    /// 输入框
    /// </summary>
    [ExecuteInEditMode]
    public class DInputField : InputField
    {
        [Serializable]
        public class KeyboardOpeningEvent : UnityEvent<float> {}
        
        [Serializable]
        public class KeyboardClosedEvent : UnityEvent {}
        
        public OnChangeEvent onInputChanged;
        public EndEditEvent onInputStart;
        public EndEditEvent onInputEnd;
        
        public KeyboardOpeningEvent onKeyboardOpening;
        public KeyboardClosedEvent onKeyboardClosed;

        private bool _inputChanged = false;
        private bool _inputEnd = false;

        private float _lastKeyboardHeight = 0;
        
        protected override void Awake()
        {
            base.Awake();
            onValueChanged.AddListener(ValueChangedHander);
            onEndEdit.AddListener(EndEditHandler);
        }

        private void ValueChangedHander(string text)
        {
            _inputChanged = true;
        }

        private void EndEditHandler(string text)
        {
            _inputEnd = true;
        }

        public virtual void OnPointerClick(PointerEventData eventData)
        {
            base.OnPointerClick(eventData);
            onInputStart?.Invoke(text);
        }

        protected override void LateUpdate()
        {
            base.LateUpdate();
            if (_inputChanged)
            {
                _inputChanged = false;
                onInputChanged?.Invoke(text);
            }
            if (_inputEnd)
            {
                _inputEnd = false;
                onInputEnd?.Invoke(text);
            }
            if (m_Keyboard != null && m_Keyboard.status == TouchScreenKeyboard.Status.Visible)
            {
                var height = UIUtil.GetKeyboardHeight();
                if (_lastKeyboardHeight != height)
                {
                    _lastKeyboardHeight = height;
                    onKeyboardOpening?.Invoke(_lastKeyboardHeight);
                }
            }
            else
            {
                if (_lastKeyboardHeight != 0)
                {
                    _lastKeyboardHeight = 0;
                    onKeyboardClosed?.Invoke();
                }
            }
        }
    }
}
